package com.jinlia.show.modules.base.wxapp.service;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.modules.base.model.form.GoodsForm;
import com.jinlia.show.modules.base.model.po.GoodsPO;
import com.jinlia.show.modules.base.model.po.ShoppingCartPO;
import com.jinlia.show.modules.base.model.query.ShoppingCartQuery;
import com.jinlia.show.modules.base.model.vo.ShoppingCartBillVO;
import com.jinlia.show.modules.base.system.entity.Goods;
import com.jinlia.show.modules.base.system.entity.GoodsAttrValue;
import com.jinlia.show.modules.base.system.service.GoodsAttrMapperService;
import com.jinlia.show.modules.base.system.service.GoodsAttrValueMapperService;
import com.jinlia.show.modules.base.system.service.GoodsMapperService;
import com.jinlia.show.modules.base.wxapp.entity.ShoppingCart;
import com.jinlia.show.modules.base.wxapp.mapper.ShoppingCartMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ShoppingCartMapperService extends ServiceImpl<ShoppingCartMapper, ShoppingCart> {

    @Autowired
    GoodsMapperService goodsMapperService;
    @Autowired
    GoodsAttrValueMapperService goodsAttrValueMapperService;
    @Autowired
    GoodsAttrMapperService goodsAttrMapperService;


    @Transactional
    public ShoppingCartBillVO addShoppingCart(ShoppingCart shoppingCart) {
        //获取默认sku属性
        shoppingCart = addDefaultShoppingCart(shoppingCart);
        if (Objects.nonNull(shoppingCart.getSkuItem()) && StringUtils.isEmpty(shoppingCart.getSkuName())) {
            //初始化sku名称
            String skuName = goodsAttrMapperService.buildSkuName(shoppingCart.getSkuItem());
            shoppingCart.setSkuName(skuName);
        }
        //校验重复的商品
        ShoppingCart oneShoppingCart = this.lambdaQuery()
                .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(ShoppingCart::getGoodsId, shoppingCart.getGoodsId())
                .eq(StringUtils.hasLength(shoppingCart.getSkuName()), ShoppingCart::getSkuName, shoppingCart.getSkuName())
                .one();
        /**
         * 移除购物车
         */
        if (shoppingCart.getId() == null) {
            this.save(shoppingCart);
        } else {
            this.lambdaUpdate()
                    .eq(ShoppingCart::getId, oneShoppingCart.getId())
                    .set(ShoppingCart::getNum, shoppingCart.getNum())
                    .set(ShoppingCart::getOriginalMoney, oneShoppingCart.getOriginalMoney())
                    .update(new ShoppingCart());
        }
        //返回购物车清单
        return this.bill(shoppingCart);
    }

    public ShoppingCart addDefaultShoppingCart(ShoppingCart shoppingCart) {
        JSONObject skuItem = shoppingCart.getSkuItem();
        if (Objects.isNull(skuItem)) {
            skuItem = goodsMapperService.getDefaultGoodsAttrValue(shoppingCart.getGoodsId());
        }
        Goods byId = goodsMapperService.getById(shoppingCart.getGoodsId());
        shoppingCart.setOriginalMoney(byId.getPrice());//商品原价
        shoppingCart.setUnitPrice(byId.getPrice());//单价
        for (String s : skuItem.keySet()) {
            skuItem.put(s, skuItem.get(s));
            //计算单价
            GoodsAttrValue byIdGoodsAttrValue = goodsAttrValueMapperService.getById(skuItem.getString(s));
            shoppingCart.setOriginalMoney(shoppingCart.getOriginalMoney().add(Objects.isNull(byIdGoodsAttrValue.getAttrValuePrice()) ? BigDecimal.ZERO : byIdGoodsAttrValue.getAttrValuePrice()));
            shoppingCart.setUnitPrice(shoppingCart.getUnitPrice().add(Objects.isNull(byIdGoodsAttrValue.getAttrValuePrice()) ? BigDecimal.ZERO : byIdGoodsAttrValue.getAttrValuePrice()));
        }
        shoppingCart.setSkuItem(skuItem);
        //设置价格
        return shoppingCart;
    }

    public List<ShoppingCartPO> getShoppingCart(ShoppingCartQuery shoppingCart) {
        List<ShoppingCart> list = this.lambdaQuery()
                .in(!CollectionUtils.isEmpty(shoppingCart.getIds()), ShoppingCart::getId, shoppingCart.getIds())
                .eq(Objects.nonNull(shoppingCart.getUserId()), ShoppingCart::getUserId, shoppingCart.getUserId())
                .eq(Objects.nonNull(shoppingCart.getEnableStatus()), ShoppingCart::getEnableStatus, shoppingCart.getEnableStatus())
                .list();
        List<ShoppingCartPO> listVO = list.stream().map(ShoppingCartPO::fromEntity).collect(Collectors.toList());
        //填充GoodsVO
        if (!CollectionUtils.isEmpty(listVO)) {
            GoodsForm goodsForm = new GoodsForm();
            goodsForm.setGoodsIds(listVO.stream().map(ShoppingCartPO::getGoodsId).collect(Collectors.toList()));
            List<GoodsPO> voList = goodsMapperService.getBaseMapper().getVOList(goodsForm);
            Map<Long, GoodsPO> collect = voList.stream().collect(Collectors.toMap(GoodsPO::getId, Function.identity()));
            listVO.forEach(i -> i.setGoodsPO(collect.get(i.getGoodsId())));
        }
        return listVO;
    }

    public ShoppingCart updateShoppingCartNum(ShoppingCart shoppingCart) {
        if (shoppingCart.getNum() <= 0) {
            this.removeById(shoppingCart.getId());
        } else {
            this.lambdaUpdate()
                    .eq(ShoppingCart::getId, shoppingCart.getId())
                    .set(ShoppingCart::getNum, shoppingCart.getNum())
                    .set(ShoppingCart::getOriginalMoney, shoppingCart.getUnitPrice().multiply(BigDecimal.valueOf(shoppingCart.getNum())))
                    .update(new ShoppingCart());
        }
        return shoppingCart;
    }

    /**
     * 购物车账单
     *
     * @param shoppingCart
     * @return
     */
    public ShoppingCartBillVO bill(ShoppingCart shoppingCart) {
        ShoppingCartBillVO shoppingCartBillVO = new ShoppingCartBillVO();
        List<ShoppingCart> list = this.lambdaQuery()
                .eq(ShoppingCart::getUserId, shoppingCart.getUserId())
                .list();
        shoppingCartBillVO.setListShoppingCart(list);
        Map<Long, Integer> shoppingCarMap = list.stream().collect(Collectors.toMap(ShoppingCart::getGoodsId, i -> i.getNum(), Integer::sum));
        shoppingCartBillVO.setShoppingCarMap(shoppingCarMap);
        //合计商品数量
        int sumCount = list.stream().map(ShoppingCart::getNum).mapToInt(Integer::intValue).sum();
        shoppingCartBillVO.setSumCount(sumCount);
        //合计金额
        BigDecimal sumMoney = list.stream().map(ShoppingCart::getOriginalMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        shoppingCartBillVO.setSumMoney(sumMoney);
        shoppingCartBillVO.setCurrentShoppingCartId(shoppingCart.getId());
        return shoppingCartBillVO;
    }
}
